package com.ww.cheappliers.common;

import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;

import org.apache.commons.lang3.StringUtils;

public class EmailUtil {
	/**
	 * 获得pop3邮件的接受时间
	 * @param msg
	 * @return
	 * @throws MessagingException
	 */
	public static Date getPop3MailReceiveDate(javax.mail.Message msg)
			throws MessagingException {
		String[] received = msg.getHeader("received");
		if (received != null)
			for (int i = 0; i < received.length; i++) {
				String dateStr = null;
				try {
					dateStr = getDateString(received[i]);
					if (dateStr != null) {
						return parseDate(dateStr);
					}
				} catch (ParseException ex) {
					ex.printStackTrace();
				}
			}

		String[] dateHeader = msg.getHeader("date");
		if (dateHeader != null) {
			String dateStr = dateHeader[0];
			try {
				return parseDate(dateStr);
			} catch (ParseException ex) {
				ex.printStackTrace();
			}
		}

		throw new RuntimeException("取不到发送时间");
	}

	private static String getDateString(String text) {
		String[] daysInDate = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
		int startIndex = -1;
		for (int i = 0; i < daysInDate.length; i++) {
			startIndex = StringUtils.lastIndexOfAny(text, daysInDate);
			if (startIndex != -1)
				break;
		}
		if (startIndex == -1) {
			return null;
		}

		String ret = text.substring(startIndex).trim();
		
		return ret.replaceFirst("(\\([a-zA-Z]{3,}\\))$", "").trim();
	}

	private static Date parseDate(String dateStr) throws ParseException {
		SimpleDateFormat dateFormat;
		DateFormatSymbols s = DateFormatSymbols.getInstance(Locale.US);
		try {
			dateFormat = new SimpleDateFormat("EEE, d MMM yy HH:mm:ss Z", s);
			return dateFormat.parse(dateStr);
		} catch (ParseException e) {
			try {
				dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", s);
				return dateFormat.parse(dateStr);
			} catch (ParseException ex) {
				dateFormat = new SimpleDateFormat("d MMM yyyy HH:mm:ss Z", s);
				return dateFormat.parse(dateStr);
			}
		}
	}
	
	public static List<String> getEmailMessage(Message mail) throws MessagingException, IOException{
		List<String> buffer = new ArrayList<String>();
		// 提取消息文本
		getMailContent((Part)mail, buffer);
		return buffer;
	}
		
	/**
	 * 获得邮件中的内容
	 * @param part
	 * @param msgBuffer
	 * @throws MessagingException
	 * @throws IOException
	 */
	private static void getMailContent(Part part, List<String> msgBuffer) throws MessagingException, IOException {
		String contenttype = part.getContentType();
		int nameindex = contenttype.indexOf("name");
		boolean conname = false;
		if (nameindex != -1)
			conname = true;
		if (part.isMimeType("text/plain") && !conname) {
			msgBuffer.add((String) part.getContent());
		} else if (part.isMimeType("text/html") && !conname) {
			msgBuffer.add((String) part.getContent());
		} else if (part.isMimeType("multipart/*")) {
			Multipart multipart = (Multipart) part.getContent();
			int counts = multipart.getCount();
			for (int i = 0; i < counts; i++) {
				getMailContent(multipart.getBodyPart(i), msgBuffer);
			}
		} else if (part.isMimeType("message/rfc822")) {
			getMailContent((Part) part.getContent(), msgBuffer);
		} else {
			// 附件？
		}
	}

	public static void main(String[] args) throws ParseException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM yyyy HH:mm:ss Z", DateFormatSymbols.getInstance(Locale.US));
		long l = dateFormat.parse("4 Jul 2001 12:08:56 -0700").getTime();
		System.err.println(l);
	}
}
